package com.mirei.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mirei.dto.UserDTO;
import com.mirei.entity.Role;
import com.mirei.dao.UserMapper;
import com.mirei.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author mirei
 */
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (null == user) {
            throw new UsernameNotFoundException("用户不存在");
        }
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        List<Role> rolesByUserId = userMapper.getRolesByUserId(user.getId());
        userDTO.setRoles(rolesByUserId);
        return userDTO;
    }
}
